import cacheFunc from '@/utils/cache.js'
import permision from "@/zego-express-video-uniapp/permission.js";
import ZegoExpressEngine from '@/zego-express-video-uniapp/lib/ZegoExpressEngine';
import {
	ZegoScenario,
	ZegoViewMode
} from '@/zego-express-video-uniapp/lib/ZegoExpressDefines'
let innerAudioContext = uni.createInnerAudioContext();
var plus_audio_TYPE = plus.audio.createPlayer();
const BindingX = uni.requireNativePlugin('bindingx'); //拖拽
import {
	AppID,
	AppSign,
	isTestEnv
} from '@/zego-express-video-uniapp/KeyCenter.js'

export default {

	data() {
		return {
			isVd: true,
			viewMode: 0,
			isSpeakerPhone: true,
			showAudio: false,
			roomID: '0006',
			streamID: '0002',
			engine: null,
			isPullPush: 'pull',
			userAudioID: '',
			// audioMsg: '正在等待对方接听...',
			audioMsg: '邀请您语音通话...',
			userAudioName: '',
			isShowAnswer: true,
			defaultMicrophone: true,
			defaultCamera: true,
			mirrorIndex: 0,
			streamID2: '123',
			// 页面高宽
			windowWidth: 260,
			windowHeight: 320,
			// 记录当前位置
			position: {
				x: 0,
				y: 0
			},
			// 判断是点击事件还是拖动事件      
			timer: false,
			isFilp: true
		}
	},
	onUnload() {
		this.destroyEngine();
		console.log('onUnload');
	},
	onBackPress() {
		this.destroyEngine();
		console.log('onBackPress');
	},
	async mounted() {
		if (uni.getSystemInfoSync().platform === 'android') {
			await permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
			await permision.requestAndroidPermission('android.permission.CAMERA');
		}
		const userInfo = cacheFunc.getCache('busUserInfo')
		this.userInfo = userInfo
		this.userAudioID = this.userInfo.id
		this.roomID = this.userInfo.id
		this.streamID = this.userInfo.id
		this.userName = this.userInfo.name
		// await this.setup();


	},

	methods: {
		getEl(el) {
			if (typeof el === 'string' || typeof el === 'number') return el;
			if (WXEnvironment) {
				return el.ref;
			} else {
				return el instanceof HTMLElement ? el : el.$el;
			}
		},
		drag_start(e) {
		 const move = this.getEl(this.$refs.move);
			let oBindingX = BindingX.bind({
				anchor: move,
				eventType: 'pan',
				props: [{
						element: move,
						property: 'transform.translateX',
						expression: `x+${this.position.x}`,
					},
					{
						element: move,
						property: 'transform.translateY',
						expression: `y+${this.position.y}`,
					}
				]
			}, (e) => {
				if (e.state === 'end') {
					if (this.timer) {
						//移动时间特别短暂 视为点击事件
						clearTimeout(this.timer);
						// 点击事件处理
						console.log('点击小窗口视频')
						// this.chekOutVd = !this.chekOutVd
					}
					BindingX.unbind({
						token: oBindingX.token,
						eventType: 'pan'
					})
					//记录位置 
					this.position.x += e.deltaX;
					this.position.y += e.deltaY;
					// x轴边界
					if (-this.position.x >= (this.windowWidth - 193)) {
						this.position.x = 193 - this.windowWidth;
					}
					if (this.position.x > 0) {
						this.position.x = 0;
					}
		 		// y 轴边界 
					if (this.position.y < 0) {
		 			this.position.y = 0;
					}
					if (this.position.y >= (this.windowHeight - 244)) {
						this.position.y = this.windowHeight - 244;
					}
					// 结束拖动
					this.endAmaier();
				} else {
					// 判断点击事件还是拖动事件
					this.timer = setTimeout(() => {
						this.timer = null;
					}, 50)
				}
		 });

		},

		// 结束拖动
		endAmaier(e) {
			const my = this.getEl(this.$refs.move);
			let result = BindingX.bind({
				eventType: 'timing',
				exitExpression: 't>200',
				props: [{
						element: my,
						property: 'transform.translateX',
						expression: "easeOutElastic(t," + this.position.x + "," + 0 +
							",200)",
					},
					{
						element: my,
						property: 'transform.translateY',
						expression: "easeOutElastic(t," + this.position.y + "," + 0 +
							",200)",
					}
				]
			}, (e) => {
				if (e.state === 'end' || e.state === 'exit') {
					BindingX.unbind({
						token: result.token,
						eventType: 'timing'
					})
				}
			});
		},
		// 挂断
		destroyEngineAudio() {
			uni.showToast({
				title: '通话结束',
				icon: 'none'
			})
			this.msgType = 6
			const msg = this.isVd ? '结束视频通话' : '结束语音通话'
			this.addMsg(msg)
			this.destroyEngine();
		},
		// 免提
		onSpeakerphone() {
			if (this.isSpeakerPhone) {
				this.isSpeakerPhone = false
				plus_audio_TYPE.setRoute(plus.audio.ROUTE_EARPIECE);
			} else {
				this.isSpeakerPhone = true
				plus_audio_TYPE.setRoute(plus.audio.ROUTE_SPEAKER);
			}

		},
		async answer() {
			// this.audioMsg = '已接通,正在语音通话...'
			// innerAudioContext.stop()
			// innerAudioContext.destroy()
			// this.answer = '邀请您语音通话'
			await this.setup();
			// this.audioMsg = '通话已连接'
			this.isShowAnswer = false
		},
		// 发起
		async openRoom(isVd) {
			// 切换到扬声器线路
			plus_audio_TYPE.setRoute(plus.audio.ROUTE_SPEAKER);
			console.log('发起语音', this.isPullPush)
			innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.loop = true;
			innerAudioContext.src =
				'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3';
			innerAudioContext.onPlay(() => {
				console.log('开始播放');
			});
			this.audioMsg = this.isPullPush == 'push' ? '正在等待对方接听...' : '邀请您语音通话...'
			this.showAudio = true
			if (this.isPullPush == 'push') {

				await this.setup(isVd);
			}
			// this.loginRoom();
			// 推流
			// this.startPublishingStream()
			// 启动音频
		},
		loginRoom() {
			let user = {
				userID: this.userAudioID,
				userName: this.userName,
			};
			this.engine.loginRoom(this.roomID, user, {
				userUpdate: true
			});

		},
		// 推流
		startPublishingStream() {
			this.engine.startPublishingStream(this.streamID);
		},
		// 推流
		// roomStreamUpdate() {
		// 	this.engine.roomStreamUpdate(this.streamID).then(res => {
		// 		console.log(res, '测试')
		// 	});
		// },
		async createEngine() {
			this.engine = await ZegoExpressEngine.createEngine(AppID, AppSign, isTestEnv, ZegoScenario.General);
			this.onRoomStateUpdate()
			// 推流状态更新回调
			this.onPlayerStateUpdate()
			// 拉流状态更新回调
			this.onPublisherStateUpdate()
			this.onRoomStreamUpdate()
			// 用户状态更新回调
			this.onRoomUserUpdate()

		},

		async destroyEngine() {
			this.isVd = true
			innerAudioContext.destroy()
			this.showAudio = false
			if (this.engine) {
				this.logoutRoom();
				this.stopPlayingStream();
				this.stopPublishingStream()
				this.stopPreview();
				this.engine = undefined;
				ZegoExpressEngine.destroyEngine(null);
			}


		},
		stopPreview() {
			console.log('停止预览')
			this.engine.stopPreview();
		},

		logoutRoom() {
			this.engine.logoutRoom(this.roomID);

		},
		// // 启动音频
		enablePlayAudio(e) {
			this.engine.mutePlayStreamAudio(this.streamID2, false);
		},

		async setup(isVd) {
			this.viewMode = ZegoViewMode.ScaleToFill
			console.log('初始化视频')
			this.keyboardHeightFlg = false

			setTimeout(async () => {

				this.engine = await ZegoExpressEngine.createEngine(AppID, AppSign, isTestEnv,
					ZegoScenario
					.General);
				this.onRoomStateUpdate()
				// 推流状态更新回调
				this.onPlayerStateUpdate()
				// 拉流状态更新回调
				this.onPublisherStateUpdate()
				this.onRoomStreamUpdate()
				// 用户状态更新回调
				this.onRoomUserUpdate()
				// 设置视频镜像模式
				// this.setVideoMirrorMode(this.mirrorIndex);


				// this.muteMicrophone(!this.defaultMicrophone);
				// 使用前置摄像头
				this.isVd && this.useFrontCamera(true);
				// // 启动视频
				this.isVd && this.enablePlayVideo();
				this.isVd && this.enableCamera(this.isVd);
				// 登录房间
				this.loginRoom()
				// 预览

				this.isVd && this.startPreview();
				console.log(this.isVd, this.streamID2, 'isVdisVdisVd')
				// 推流
				this.startPublishingStream()
				// 拉流
				this.startPlayingStream(this.streamID2)
				// // 启动音频
				this.enablePlayAudio();


			}, 200)

			// // 启动视频
			// if (this.isVd) {
			// 	this.enablePlayVideo();
			// }

			// 设置视频镜像模式
			// this.setVideoMirrorMode(this.mirrorIndex);
			// this.enableCamera(this.isVd);
			// this.muteMicrophone(!this.defaultMicrophone);
			// 使用前置摄像头
			// this.useFrontCamera(true);




		},
		useFrontCamera(e) {
			this.engine.useFrontCamera(e);
		},
		enableCamera(e) {
			this.engine.enableCamera(e);
		},
		muteMicrophone(e) {
			this.engine.muteMicrophone(e);
		},
		setVideoMirrorMode(e) {
			this.engine.setVideoMirrorMode(e);
		},
		startPreview() {
			this.engine.startPreview();
		},
		enablePlayVideo(e) {
			this.engine.mutePlayStreamVideo(this.streamID2, false);
		},
		startPlayingStream() {
			this.engine.startPlayingStream(this.streamID2)
		},
		// 用户状态更新回调
		onRoomUserUpdate() {
			this.engine.on('roomUserUpdate', (roomID, updateType, userList) => {
				console.warn('用户状态更新回调', updateType, userList);
				if (updateType == 0 && userList.length !== 0 && this.userAudioID != userList[0].userID) {
					this.audioMsg = '已接通,正在语音通话...'
					// innerAudioContext.stop()
					innerAudioContext.destroy()
				}
				if (updateType == 1) {
					this.destroyEngine()
				}

			});
		},
		// 停止推流
		stopPublishingStream() {
			this.engine.stopPublishingStream(this.streamID);
		},
		// 停止拉流
		stopPlayingStream() {
			this.engine.stopPlayingStream(this.streamID2);
		},
		// 推流接口成功后
		onPlayerStateUpdate() {
			this.engine.on("publisherStateUpdate", (streamID, state, errorCode, extendedData) => {
				// 调用推流接口成功后，当推流器状态发生变更，如出现网络中断导致推流异常等情况，SDK在重试推流的同时，会通过该回调通知
				console.log('推状态更新回调', streamID, state, errorCode, extendedData, '')

			});

		},
		// 推流接口成功后
		onRoomStreamUpdate() {
			this.engine.on("roomStreamUpdate", (roomID, updateType, streamList) => {
				// 调用推流接口成功后，当推流器状态发生变更，如出现网络中断导致推流异常等情况，SDK在重试推流的同时，会通过该回调通知
				// this.streamID2 = streamList[0].streamID
				console.log('远端用户推送的 “streamID”', this.streamID2, updateType, streamList)
				if (updateType == 0) {
					// 拉流 (传入对方的流id)

				}
			});

		},
		onPublisherStateUpdate() {
			this.engine.on('playerStateUpdate', (streamID, state, errorCode, extendedData) => {
				console.log('拉流状态更新回调', streamID, state, errorCode, extendedData, '')
				// 拉流状态更新回调
				// this.audioMsg = '已接通,正在语音通话...'
				// innerAudioContext.destroy()
			})
		},
		onRoomStateUpdate() {
			this.engine.on('roomStateUpdate', (roomID, state, errorCode, extendedData) => {
				console.log(state, '与房间连接状态连接')
				if (state == 'DISCONNECTED') {
					// 与房间断开了连接
					console.log('与房间断开了连接')
				}

				if (state == 'CONNECTING') {
					// 与房间尝试连接中 
					console.log('与房间尝试连接中')
				}

				if (state == 'CONNECTED') {
					console.log('与房间连接成功')
					// 与房间连接成功
				}
			})
		},
	}
}
